//
//  TakePhotoBaseViewController.swift
//  CalligraphyUniversal
//
//  Created by 李雷川 on 2017/9/18.
//  Copyright © 2017年 李雷川. All rights reserved.
//

import UIKit
import FZSFCommonTools

public class TakePhotoBaseViewController: UIViewController {
    lazy var squareView:Square = {
        let squareView = Square()
        return squareView
    }()
    
    lazy var maskView:UIView = {
        let  maskView = UIView()
        maskView.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.4)
        return maskView
    }()
   
    lazy var scrrentImageView:UIImageView = {
        let imageView = UIImageView()
        return imageView
    }()
    
    lazy var infoLabel:UILabel = {
        let label = UILabel.createLabel(textColor: UIColor(hexString: "#D7D7D7")!, font: AppFonts.normal, defaultText: "将作品放入框内")
        return label
    }()

    lazy var takePhotoButton:UIButton  = {
        let button = UIButton(type: .custom)
        button.setImage(UIImage.init(named:imageNamed(imageName: "camera")), for: .normal)
        button.setImage(UIImage.init(named:imageNamed(imageName: "camera_sel")), for: .highlighted)
        button.addTarget(self, action: #selector(tapTakePhoto(sender:)), for: .touchUpInside)
        return button
    }()
    
    lazy var switchCameraButton:UIButton  = {
        let button = UIButton(type: .custom)
        button.setImage(UIImage.init(named:imageNamed(imageName: "switch_camera")), for: .normal)
        button.addTarget(self, action: #selector(tapSwitchCamera(sender:)), for: .touchUpInside)
        return button
    }()
    
    lazy var slider:UISlider  = {
        let slider = UISlider()
        slider.minimumValue = 0.25
        slider.maximumValue = view.bounds.size.width > view.bounds.size.height ? 0.5:0.75
        slider.isContinuous = true
        slider.value = percent
        
        let minImage = UIImage.init(named: imageNamed(imageName: "min_track"))
        let maxImage = UIImage.init(named: imageNamed(imageName: "max_track"))
        slider.setMinimumTrackImage(minImage?.stretchableImage(withLeftCapWidth: 6, topCapHeight: 4), for: .normal)
        slider.setMaximumTrackImage(maxImage?.stretchableImage(withLeftCapWidth: 6, topCapHeight: 4), for: .normal)
        
        slider.maximumValueImage = UIImage.init(named: imageNamed(imageName: "plus"))
        slider.minimumValueImage = UIImage.init(named: imageNamed(imageName: "minus"))
        slider.addTarget(self, action: #selector(valueChanged(sender:)), for: .valueChanged)
        
        slider.transform = CGAffineTransform.init(rotationAngle: -1.57079633)
        return slider
    }()
    
    
    lazy var closeButton:UIButton  = {
        let closeButton = UIButton()
        closeButton.setImage(UIImage.init(named:imageNamed(imageName: "arrow_down")), for: .normal)
        closeButton.addTarget(self, action: #selector(tapClose(sender:)), for: .touchUpInside)
        return closeButton
    }()
    
    var percent:Float = 0.75
    let yOffSet:CGFloat = 30
    var isFrontCamera = true
    public var isCanSwitchCamera = true
    public var startEvaluateClosure:((_ image:UIImage,_ viewController:UIViewController,_ faildHandle:((_ code:Int)->Void)?)->())?
    
    public init() {
        super.init(nibName: nil, bundle: nil)
    }
    
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override public func viewDidLoad() {
        super.viewDidLoad()
        if let lastSquarePercent = UserDefaults.standard.value(forKey: AppUserDefault.squarePercent) as? Float{
            percent = lastSquarePercent
        }
        else{
            percent = view.bounds.size.width > view.bounds.size.height ? 0.5:0.75
            UserDefaults.standard.setValue(percent, forKey: AppUserDefault.squarePercent)
        }
      
        if(UIDevice.current.model == "iPhone" || !isCanSwitchCamera){
            isFrontCamera = false
            slider.isHidden = true
        }
    }

    override public var shouldAutorotate: Bool{
        return false
    }

    override public var prefersStatusBarHidden: Bool{
        return true
    }
    
    override public var preferredStatusBarUpdateAnimation: UIStatusBarAnimation{
        return .slide
    }
    
    override public func viewWillAppear(_ animated: Bool) {
        self.navigationController?.setNavigationBarHidden(true, animated: true)
    }
    
    func initUI(){
        view.backgroundColor = UIColor.black
        setupMaskView()
        setupSquareView()
        setupScreenImageView()
        setupSlider()
        setupInfoLabel()
        setupSwitchCameraButton()
        setupTakePhotoButton()
        setupCloseButton()
    }
    
    
    //NavigationBar:主菜单、添加课程
    func setupMaskView(){

        view.addSubview(maskView)
        maskView.snp.makeConstraints { (make) in
            make.edges.equalTo(view)
            
        }
        updateMaskLayer()
    }
    
    func setupSquareView(){
        self.view.addSubview(squareView)
        squareView.snp.makeConstraints { (make) in
            make.width.height.equalTo( self.view.width > self.view.height ? self.view.snp.height:self.view.snp.width).multipliedBy(percent)
            make.centerX.equalTo(self.view)
            make.centerY.equalTo(self.view).offset(-yOffSet)
        }
    }
    
    func setupScreenImageView(){
        scrrentImageView = UIImageView()
        scrrentImageView.contentMode = .scaleAspectFill
        view.addSubview(scrrentImageView)
        scrrentImageView.snp.makeConstraints { (make) in
            make.edges.equalTo(view)
        }
        
    }

    func setupSlider(){
        let width = view.width > view.height ? view.width * 0.3:view.height * 0.4
        let height:CGFloat = 44
        view.addSubview(slider)
        slider.snp.makeConstraints { (make) in
            make.trailing.equalTo(view).offset((width/2 - height/2))
            make.height.equalTo(height)
            make.width.equalTo(width)
            make.centerY.equalTo(squareView)
        }
    }
    
    func setupInfoLabel(){
        view.addSubview(infoLabel)
        infoLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(view)
            make.top.equalTo(squareView.snp.bottom).offset(16)
        }
    }
    
    func setupSwitchCameraButton(){
        view.addSubview(switchCameraButton)
        switchCameraButton.snp.makeConstraints { (make) in
            make.trailing.equalTo(-4)
            make.top.equalTo(15+topMargin)
        }
    }
    
    func setupTakePhotoButton(){
        view.addSubview(takePhotoButton)
        takePhotoButton.snp.makeConstraints { (make) in
            make.centerX.equalTo(view)
            make.bottom.equalTo(-40)
        }
    }
    
    func updateMaskLayer(){
        let squareWidth = view.width>view.height ? view.height * CGFloat(percent):view.width * CGFloat(percent)
        let squareHeight = squareWidth
        let maskLayer = CAShapeLayer()
        let path = CGMutablePath()
        path.addRect(CGRect.init(x: 0, y: 0, width: view.width, height: (view.height - squareHeight)/2 - yOffSet))
        path.addRect(CGRect.init(x: 0, y: (view.height - squareHeight)/2 - yOffSet, width: (view.width - squareWidth)/2, height:squareHeight))
        path.addRect(CGRect.init(x: 0, y: view.height/2 + squareHeight/2 - yOffSet, width:view.width , height: (view.height - squareHeight)/2 + yOffSet))
        path.addRect(CGRect.init(x: view.width/2 + squareWidth/2, y: (view.height - squareHeight)/2 - yOffSet, width:(view.width - squareWidth)/2, height: squareHeight))
        maskLayer.path = path
        maskView.layer.mask = maskLayer
    }
    
    func setupCloseButton(){
        view.addSubview(closeButton)
        closeButton.snp.makeConstraints { (make) in
            make.right.equalTo(takePhotoButton.snp.left).offset(-64)
            make.centerY.equalTo(takePhotoButton)
        }
    }
    
    func generateImageSuccess(image:UIImage){
        let newImage = self.croppingImage(originalImage: image)
        if let scaleImage = newImage.resize(size: CGSize.init(width: 500, height: 500)){
            let editImageViewController = EditPictureViewController(percent: percent, image: scaleImage)
            editImageViewController.startEvaluateClosure = {
                [weak self](image,vc,handle)in
                self?.startEvaluateClosure?(image, vc, handle)
            }
            self.navigationController?.pushViewController(editImageViewController, animated: false)
        }
        takePhotoButton.isEnabled = true
    }
    
    
    func croppingImage(originalImage:UIImage) ->UIImage{
        self.scrrentImageView.image = originalImage
        let screenshotImage = self.scrrentImageView.generateImage()
        let deviceScale = UIScreen.main.scale
        let cgImage = screenshotImage?.cgImage?.cropping(to: CGRect(x: squareView.frame.origin.x*deviceScale, y:  squareView.frame.origin.y*deviceScale, width: squareView.width * deviceScale, height: squareView.height * deviceScale))
        scrrentImageView.image = nil
        let cropImage = UIImage.init(cgImage: cgImage!)
        return cropImage
    }
    
    //MARK Action
    @objc func tapSwitchCamera(sender:UIButton){
        isFrontCamera = !isFrontCamera
        slider.isHidden = !isFrontCamera
        if(isFrontCamera){
            if let lastSquarePercent = UserDefaults.standard.value(forKey: AppUserDefault.squarePercent) as? Float{
                percent = lastSquarePercent
            }
        }
        else{
             percent = view.bounds.size.width > view.bounds.size.height ? 0.5:0.75
        }
        self.updateMaskLayer()
        self.squareView.snp.remakeConstraints { (make) in
            make.width.height.equalTo( self.view.width > self.view.height ? self.view.snp.height:self.view.snp.width).multipliedBy(percent)
            make.centerX.equalTo(self.view)
            make.centerY.equalTo(self.view).offset(-self.yOffSet)
        }
        self.view.layoutIfNeeded()
    }
    
    
    
    @objc func valueChanged(sender:UISlider){
        percent = sender.value
        UserDefaults.standard.setValue(percent, forKey: AppUserDefault.squarePercent)
        self.updateMaskLayer()
        self.squareView.snp.remakeConstraints { (make) in
            make.width.height.equalTo( self.view.width > self.view.height ? self.view.snp.height:self.view.snp.width).multipliedBy(percent)
            make.centerX.equalTo(self.view)
            make.centerY.equalTo(self.view).offset(-self.yOffSet)
        }


        self.view.layoutIfNeeded()
    }
    
    

    @objc func tapClose(sender:UIButton){
        self.dismiss(animated: true, completion: nil)
    }
    
    
    @objc func tapTakePhoto(sender:UIButton){
        sender.isEnabled = false
        self.navigationController?.setNavigationBarHidden(true, animated: false)
        if(isFrontCamera){
            let countDownView = CountDownView()
            view.addSubview(countDownView)
            countDownView.start()
            countDownView.finishClosure = {[unowned self]()in
                self.startGeneragteImage()
            }
            countDownView.snp.makeConstraints { (make) in
                make.edges.equalTo(view)
            }
        }
        else{
            self.startGeneragteImage()
        }
    
    }
    
    func startGeneragteImage() {
        
    }
    func generateImageFaild(){
        takePhotoButton.isEnabled = true
    }
    
}
